using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Xml.Serialization;
using CodePlex.DnD4eCampaignManager.DnD4e;
using CodePlex.DnD4eCampaignManager.Repositories.Interfaces;

namespace CodePlex.DnD4eCampaignManager.Repositories
{
    public class StoryArcRepository : IStoryArcRepository
    {
        private readonly string _campaignName;

        public StoryArcRepository(string campaignName)
        {
            _campaignName = campaignName;
            if ( !Directory.Exists(_campaignName) )
            {
                Directory.CreateDirectory(_campaignName);
            }
        }

        public StoryArc CampaignRootArc()
        {
            return GetByName(_campaignName);
        }

        public ReadOnlyCollection<string> GetAllNames()
        {
            List<string> storyArcNames = new List<string>();
            foreach ( string file in Directory.GetFiles(_campaignName, "*.StoryArc") )
            {
                storyArcNames.Add(file.Replace(".StoryArc", string.Empty).Replace(_campaignName, string.Empty).Replace("\\", string.Empty));
            }
            return storyArcNames.AsReadOnly();
        }

        public StoryArc GetByName(string playerCharacterName)
        {
            if ( playerCharacterName == string.Empty )
            {
                return null;
            }
            XmlSerializer xmlSerializer = new XmlSerializer(typeof ( StoryArc ));
            string monsterPath = string.Format("{1}\\{0}.StoryArc", playerCharacterName, _campaignName);
            using ( TextReader textReader = new StreamReader(monsterPath) )
            {
                StoryArc storyArc = xmlSerializer.Deserialize(textReader) as StoryArc;
                return storyArc;
            }
        }

        public void Save(StoryArc playerCharacter)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof ( StoryArc ));
            using ( TextWriter textWriter = new StreamWriter(string.Format("{1}\\{0}.StoryArc", playerCharacter.ArcName, _campaignName)) )
            {
                xmlSerializer.Serialize(textWriter, playerCharacter);
            }
        }
    }
}